package com.mrper.ui.brand;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;

import com.miguo.activity.callback.listener.GoodsScrollListener;
import com.miguo.ui.R;
import com.miguo.ui.databinding.ActivityBrandDetailBinding;
import com.mrper.ext.adapter.fragment.SwitchFragmentAdapter;
import com.mrper.ext.annotation.BackActionEvent;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.dialog.ShareLinkActionSheetDialog;
import com.mrper.ext.event.BrandDetailGoodsListViewScrollStateChangedEvent;
import com.mrper.ext.uibase.BasicActivity;
import com.mrper.ext.widget.BrandSortView;
import com.mrper.model.entry.brand.BrandThemeInfoEntry;
import com.mrper.model.share.ShareLinkParamsInfoEntry;
import com.mrper.util.DeviceUtil;
import com.mrper.util.ViewUtil;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.IntEvaluator;
import com.nineoldandroids.animation.ValueAnimator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;


/**
 * 品牌内页页面
 */
@BackActionEvent
@ContentView(R.layout.activity_brand_detail)
public class   BrandDetailActivity extends BasicActivity<ActivityBrandDetailBinding> implements BrandSortView.OnSortChangedListener, ViewPager.OnPageChangeListener {

    private static final int MAX_TAB_COUNT = 3;//Tab数量

    private BrandThemeInfoEntry themeInfo;//品牌主题信息
    private List<FragmentBrandDetailListContent> fragments = new ArrayList<>();//页面fragment
    private int recordImageThemeHeight = 0;//记录的主题图片的高度
    private boolean isImageThemeAnimating = false;//是否是主题图片正在动画中
    private ShareLinkActionSheetDialog shareDialog;//分享对话框

    @Override
    @SuppressWarnings("all")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("brandThemeInfo"))
            themeInfo = (BrandThemeInfoEntry) intent.getSerializableExtra("brandThemeInfo");
        EventBus.getDefault().register(this);
        initShareDialog(); //初始化分享对话框
        dataBinder.setOnClickEvent(this);
        dataBinder.setTitle(themeInfo.title + "  " +themeInfo.name);
        dataBinder.brandSortView.setOnSortChangedListener(this);
        initImageTheme(); //初始化主题图片
        initOtherLayout();//初始化其他布局
    }

    //初始化其他布局
    @SuppressWarnings({"unchecked","deprecation"})
    private void initOtherLayout() {
        for (int i = 0; i < MAX_TAB_COUNT; i++) {
            Bundle argument = new Bundle();
            argument.putInt("brandThemeId", themeInfo.id);
            FragmentBrandDetailListContent fragment = ViewUtil.getFragmentInstance(FragmentBrandDetailListContent.class, argument);
            fragments.add(fragment);
        }
        dataBinder.flContainer.setAdapter(new SwitchFragmentAdapter(getSupportFragmentManager(), fragments));
        if (Build.VERSION.SDK_INT >= 23) dataBinder.flContainer.addOnPageChangeListener(this);
        else dataBinder.flContainer.setOnPageChangeListener(this);
        dataBinder.flContainer.postDelayed(new Runnable() {
            @Override
            public void run() {
                fragments.get(0).setSortState(BrandSortView.SORT_DEFAULT, BrandSortView.MODE_NONE); //默认加载第一页
            }
        }, 500);
    }

    //初始化主题图片
    private void initImageTheme() {
        dataBinder.setThemeImageUrl(themeInfo.brand_image);
        ViewGroup.LayoutParams layoutParams = dataBinder.imgTheme.getLayoutParams();
        layoutParams.width = DeviceUtil.getScreenWidth(context);
        layoutParams.height = (int) (layoutParams.width * 0.40f);
        recordImageThemeHeight = layoutParams.height;//记录的主题图片的高度,用于动画
        dataBinder.imgTheme.setLayoutParams(layoutParams);
        dataBinder.imgTheme.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    //初始化分享对话框
    private void initShareDialog() {
        shareDialog = new ShareLinkActionSheetDialog();
        shareDialog.setShareActivity(this);
        shareDialog.setShareParams(new ShareLinkParamsInfoEntry(themeInfo.name, "", themeInfo.theme_image, themeInfo.share_url));
    }

    @Override
    public void onSortChanged(int position, int sort, int mode) {
        dataBinder.flContainer.setCurrentItem(position, true);
        fragments.get(position).setSortState(sort, mode);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        dataBinder.brandSortView.setCurrentPosition(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Subscribe
    public void onBrandDetailGrodListViewScrollStateChangedEvent(BrandDetailGoodsListViewScrollStateChangedEvent event) {
        if(!isImageThemeAnimating) {
            int currentVisibility = dataBinder.imgTheme.getVisibility();
            startImageThemeAnimation(currentVisibility, event.direction); //启动动画
        }
    }

    /**
     * 执行主题图片动画
     * @param currentVisibility 当前主题图片的显示状态
     * @param direction 获取的列表滚动的方向
     */
    private void startImageThemeAnimation(int currentVisibility, GoodsScrollListener.Direction direction) {
        final int startValue, endValue;
        final int visibility;
        if(direction == GoodsScrollListener.Direction.DOWN){
            startValue = 0;
            endValue = recordImageThemeHeight;
            visibility = View.VISIBLE;
        }else{
            startValue = recordImageThemeHeight;
            endValue = 0;
            visibility = View.GONE;
        }
        if(currentVisibility == visibility) return; //状态相同，不执行该动画
        ValueAnimator valueAnimator = new ValueAnimator();
        valueAnimator.setIntValues(startValue, endValue);
        valueAnimator.setInterpolator(new AccelerateInterpolator());
        valueAnimator.setDuration(500);
        valueAnimator.setEvaluator(new IntEvaluator(){
            @Override
            public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
                int result = (int)(startValue + (endValue - startValue) * fraction);
                ViewGroup.LayoutParams layoutParams = dataBinder.imgTheme.getLayoutParams();
                layoutParams.height = result;
                dataBinder.imgTheme.setLayoutParams(layoutParams);
                return result;
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isImageThemeAnimating = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                dataBinder.imgTheme.setVisibility(visibility);
                isImageThemeAnimating = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator.start();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgBack:
                this.finish();
                break;
            case R.id.imgShare:
                if(shareDialog!=null) {
                    shareDialog.show(getSupportFragmentManager(), "share_dialog");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
